import { useState, useEffect } from "react";
import dayjs from "dayjs";
import { goodsSkuListDeleteList, goodsSkuListModifyList } from "@/api/modules/goodsSkuList";
import { myGoodsDetail, myGoodsList, GoodsItemModel, GoodsItemskuListModel, MyGoodsListSendModel } from "@/api/modules/goods";
import { setSku_list, setSpec_list, SkuListItem, SpecListItem } from "@/views/goods/set_Sku_data";
import { categoryGetTwo, CategoryGetReturnItemModel } from "@/api/modules/category";
import { Button, Space, Table, Tag, Tooltip, Form, Modal, message, InputNumber, Radio, RadioChangeEvent, Popconfirm } from "antd";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import useSyncState from "@/hooks/useSyncState";
import Cimage from "@/components/Cimage";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
interface GoodsItemTableModel extends GoodsItemModel {
	sku_list?: SkuListItem[];
	spec_list?: SpecListItem[];
	parentIdText?: string;
}
const goodsSkuList = () => {
	/** 初始化数据 */
	const [loading, setLoading] = useState<boolean>(false);
	const [tableData, setTableData] = useState<GoodsItemTableModel[]>([]);
	const [listQuery, setListQuery] = useState<MyGoodsListSendModel>({
		page: 1,
		size: 10,
		total: 0
	});
	const [categoryTwoData, setCategoryTwoData, getCategoryTwoData] = useSyncState<CategoryGetReturnItemModel[]>([]);
	/**
	 * 获取商品列表数据
	 * @param listQueryRef 商品列表查询参数
	 * @description
	 * 1. 调用myGoodsList接口获取商品基础列表
	 * 2. 遍历列表项，调用myGoodsDetail接口获取每个商品的详细信息
	 * 3. 处理sku和spec数据后合并到最终表格数据
	 * 4. 处理加载状态和数据异常情况
	 */
	async function getList(listQueryRef: MyGoodsListSendModel) {
		setLoading(true);
		myGoodsList(listQueryRef)
			.then(({ code, data }) => {
				if (code === 0) {
					setListQuery({
						...listQueryRef,
						total: data!.total
					});
					const tableData = data!.list || [];
					let flag = 0;
					const newTableData: GoodsItemTableModel[] = [];
					for (let i = 0; i < tableData.length; i++) {
						myGoodsDetail({ goodsId: tableData[i].id }).then(({ code, data }) => {
							if (code === 0) {
								newTableData.push({
									...data,
									sku_list: setSku_list(data, data.none_sku ? "none" : ""),
									spec_list: setSpec_list(data.skuList, data.none_sku ? "none" : ""),
									parentIdText: categoryFilter(tableData[i].parentId, categoryTwoData)
								});
								flag++;
								if (flag === tableData.length) {
									newTableData.forEach(item => {
										item.parentIdText = categoryFilter(item.parentId, getCategoryTwoData());
									});
									setTableData(newTableData);
									setLoading(false);
									console.log(newTableData, getCategoryTwoData(), "商品数据");
								}
							}
						});
					}
				} else {
					setTableData([]);
					setLoading(false);
				}
			})
			.catch(() => {
				setTableData([]);
				setLoading(false);
			});
	}
	/** 表格分类回显文字部分 */
	async function getCategoryTwo() {
		return new Promise((resolve, reject) => {
			// 获取二级分类
			categoryGetTwo().then(({ code, data }) => {
				if (code === 0) {
					setCategoryTwoData(data);
					resolve(data);
				} else reject();
			});
		});
	}
	// 根据传入分类id返回分类名称
	function categoryFilter(parentId: number | string, categoryList: CategoryGetReturnItemModel[]) {
		if (categoryList?.length === 0) return "空";
		let categoryName = "";
		categoryList?.forEach(item => {
			if (item.id === parentId) categoryName = item.name;
		});
		return categoryName;
	}
	// 分页器变化回调
	function handleTableChange(pagination: any) {
		const listQueryRef: MyGoodsListSendModel = {
			page: pagination.current,
			size: pagination.pageSize,
			total: pagination.total
		};
		setListQuery(listQueryRef);
		getList(listQueryRef);
	}

	/* 对话框相关 */
	interface SkuValue {
		[propName: string]: any;
	}
	interface Dialog {
		visible: boolean;
		title: string;

		id?: number | string;
		goodsId: number | string;
		price: number | null;
		stock_num: number | null;

		goodsItem: GoodsItemTableModel | null;
		skuValue: SkuValue;
	}
	const [form] = Form.useForm();
	const [dialogLoading, setDialogLoading] = useState<boolean>(false);
	const [dialog, setDialog] = useState<Dialog>({
		visible: false,
		title: "",

		id: "", // sku列表id
		goodsId: "", // 当前商品 id
		price: null, // 该sku列表价格
		stock_num: null, // 该sku列表库存
		goodsItem: null, // 单个商品数据
		skuValue: {} // 选择的sku列表id
	});
	function openDialog(goodsItem: GoodsItemTableModel, type: string, skuListItem?: SkuListItem) {
		// 打开对话框
		setDialog({ ...dialog, visible: true });
		let newDialog: Dialog = {
			...dialog
		};
		switch (type) {
			case "add":
				newDialog = {
					...newDialog,
					title: "添加规格列表",
					goodsId: goodsItem.id,
					goodsItem: goodsItem,
					visible: true
				};
				break;
			case "modify":
				newDialog = {
					...newDialog,
					title: "修改规格列表",
					goodsId: goodsItem.id,
					goodsItem: goodsItem,
					id: skuListItem?._id,
					price: Number(skuListItem?.price),
					stock_num: Number(skuListItem?.stock),
					visible: true
				};

				// 确定sku id
				skuListItem?.indexList.forEach(item => {
					goodsItem.skuList[item.parentIndex].vId = goodsItem.skuList[item.parentIndex].v[item.sonIndex].id;
					newDialog.skuValue[goodsItem.skuList[item.parentIndex].k_s] = goodsItem.skuList[item.parentIndex].v[item.sonIndex].id;
				});
				// 修改的时候回显数据
				form.setFieldsValue({
					price: skuListItem?.price,
					stock_num: skuListItem?.stock,
					...newDialog.skuValue
				});
				break;
		}
		setDialog(newDialog);
	}
	function closeDialog() {
		// 关闭对话框
		const dialog = {
			visible: false,
			title: "",

			id: "", // sku列表id
			goodsId: "", // 当前商品 id
			price: null, // 该sku列表价格
			stock_num: null, // 该sku列表库存
			goodsItem: null, // 单个商品数据
			skuValue: {} // 选择的sku列表id
		};
		form.resetFields();
		setDialog(dialog);
	}
	// 提交新增sku规格表单
	const onDialogFinish = async (form: any) => {
		console.log("form", form);
		if (!form.stock_num) {
			message?.warning("请输入该选项库存");
			return;
		}
		if (!form.price) {
			message?.warning("请输入该选项价格");
			return;
		}
		if (Object.keys(dialog.skuValue).length !== dialog.goodsItem?.skuList.length) {
			message?.warning("请选择规格列表");
			return;
		}
		setDialogLoading(true);
		try {
			const { code, msg } = await goodsSkuListModifyList({
				id: dialog.id ? dialog.id : undefined,
				parentId: dialog.goodsId,
				price: form.price,
				stock_num: form.stock_num,
				...dialog.skuValue
			});
			if (code === 0) {
				message?.success(msg);
				getList(listQuery);
				closeDialog();
			}
		} finally {
			setDialogLoading(false);
		}
	};
	// 修改sku规格表单失败回调
	const onDialogFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 点击确定按钮
	const handleDialogOk = () => {
		form.submit();
	};
	// 选择sku规格回调
	function skuFormSkuChange(item: GoodsItemskuListModel, e: RadioChangeEvent) {
		console.log("skuFormSkuChange", item, e.target.value);
		// 选择单项规格回调
		item.vId = e.target.value;
		const skuDialogRef = {
			...dialog
		};
		skuDialogRef.skuValue[item.k_s] = item.vId;
		setDialog(skuDialogRef);
	}
	/** 删除sku列表item */
	async function removeSkuListItem(id: number) {
		showFullScreenLoading();
		try {
			const { code, msg } = await goodsSkuListDeleteList({ ids: id.toString() });
			if (code === 0) {
				message?.success(msg);
				getList(listQuery);
			}
		} finally {
			tryHideFullScreenLoading();
		}
	}
	useEffect(() => {
		getCategoryTwo().then(() => {
			getList(listQuery);
		});
	}, []);
	const columns: any[] = [
		{
			title: "上架时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "15%",
			render: (createTime: number) => (
				<Tooltip placement="topLeft" title={dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}>
					{dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}
				</Tooltip>
			)
		},
		{
			title: "商品封面",
			dataIndex: "iconId",
			key: "iconId",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "10%",
			className: "iconId_tableClass",
			render: (_: any, record: GoodsItemTableModel) => <Cimage src={record.iconId[0].url} width={80} height={80}></Cimage>
		},
		{
			title: "商品名称",
			dataIndex: "name",
			key: "name",
			align: "center",
			width: "20%"
		},
		{
			title: "商品标签",
			dataIndex: "hot",
			key: "hot",
			align: "center",
			width: "10%",
			render: (_: any, record: GoodsItemTableModel) => <Tag color="green">{record.hot}</Tag>
		},
		{
			title: "商品类别",
			dataIndex: "parentId",
			key: "parentId",
			align: "center",
			width: "10%",
			render: (_: any, record: GoodsItemTableModel) => <>{record.parentIdText}</>
		},
		{
			title: "商品库存",
			dataIndex: "stock_num",
			key: "stock_num",
			align: "center",
			width: "10%"
		},
		{
			title: "规格信息",
			dataIndex: "none_sku",
			key: "none_sku",
			align: "center",
			width: "10%",
			render: (_: any, record: GoodsItemTableModel) => (
				<Tag color={record.none_sku ? "red" : "blue"}>{record.none_sku ? "无规格商品" : "多个规格商品"}</Tag>
			)
		},
		{
			title: "操作",
			align: "center",
			key: "action",
			width: "15%",
			render: (_: any, record: GoodsItemTableModel) => (
				<Space wrap>
					<Button
						type="primary"
						disabled={record.none_sku ? true : false}
						icon={<PlusOutlined />}
						onClick={e => {
							e.stopPropagation();
							openDialog(record, "add");
						}}
					>
						添加规格列表
					</Button>
				</Space>
			)
		}
	];
	function expandedRowRenderItem(record: GoodsItemTableModel) {
		return (
			<>
				{record.sku_list?.map((value: SkuListItem, idx: number) => (
					<div className="flex items-center pb-10 ml-20 pt-10 ml-20" key={value._id}>
						<span>{idx + 1} 、</span>
						<Cimage src={value.image} width={50} height={50} />
						<span className="text-16 ml-20">{value.sku_name_arr.toString()}</span>
						<span className="text-16 ml-20">库存: x{value.stock}</span>
						<span className="text-16 ml-20">价格: ￥{value.price}</span>
						<Button type="primary" className="ml-20" onClick={() => openDialog(record, "modify", value)}>
							修改
						</Button>
						<Popconfirm
							title="确定执行该操作吗？"
							className="ml-20"
							onConfirm={() => removeSkuListItem(value._id)}
							okText="Yes"
							cancelText="No"
						>
							<Button type="primary" danger>
								删除
							</Button>
						</Popconfirm>
					</div>
				))}
			</>
		);
	}
	return (
		<div className="goodsSkuList">
			<div className="goodsSkuList__title flex items-center justify-between mb-10">
				<Space className="flex items-center" size="large">
					<span className="text-18 font-bold">规格列表</span>
				</Space>
				<Space className="flex items-center">
					<Button
						type="primary"
						icon={<SearchOutlined />}
						onClick={() => {
							getList(listQuery);
						}}
					>
						查询
					</Button>
				</Space>
			</div>
			<div className="goodsSkuList__content">
				<Table
					loading={loading}
					bordered={false}
					dataSource={tableData}
					columns={columns}
					rowKey={record => record.id}
					scroll={{ x: true }}
					pagination={{
						current: listQuery.page, // 当前页码
						pageSize: listQuery.size, // 每页条数
						total: listQuery.total, // 数据总数
						showSizeChanger: true, // 显示每页条数切换器
						showQuickJumper: true // 显示快速跳转输入框
					}}
					expandable={{
						expandedRowRender: expandedRowRenderItem,
						rowExpandable: record => !record.none_sku,
						expandRowByClick: true
					}}
					onChange={pagination => handleTableChange(pagination)} // 分页变化回调
				/>
			</div>
			{/* 添加sku规格弹窗 */}
			<Modal
				width={600}
				title={dialog.title}
				open={dialog.visible}
				destroyOnClose={true}
				onOk={handleDialogOk}
				confirmLoading={dialogLoading}
				onCancel={closeDialog}
			>
				<Form
					form={form}
					preserve={false}
					size="middle"
					autoComplete="off"
					onFinish={onDialogFinish}
					onFinishFailed={onDialogFinishFailed}
				>
					<Form.Item
						label="价格"
						name="price"
						rules={[
							{ required: true, message: "请输入该选项价格" },
							{
								pattern: /^\d+(\.\d{0,2})?$/,
								message: "最多保留两位小数！"
							}
						]}
					>
						<InputNumber max={9999999} precision={2} min={0} step={1} className="w-full!" addonAfter={<>￥</>} />
					</Form.Item>
					<Form.Item
						label="库存"
						name="stock_num"
						rules={[
							{ required: true, message: "请输入该选项剩余库存" },
							{
								pattern: /^-?\d+$/,
								message: "请输入整数！"
							}
						]}
					>
						<InputNumber className="w-full!" max={9999999} precision={0} min={0} step={1}></InputNumber>
					</Form.Item>
					{dialog.goodsItem?.skuList.map((item, index) => (
						<Form.Item label={item.k} name={item.k_s} key={index} rules={[{ required: true, message: "请选择规格项" }]}>
							<Radio.Group optionType="button" buttonStyle="solid" onChange={e => skuFormSkuChange(item, e)}>
								{item.v.map((song, idx) => (
									<Radio value={song.id} key={idx}>
										<Space>
											{song.previewImgUrl && song.previewImgUrl?.length > 0 ? (
												<Cimage src={song.previewImgUrl[0].url} width={30} height={30} isPreview={false}></Cimage>
											) : null}
											<span>{song.name}</span>
										</Space>
									</Radio>
								))}
							</Radio.Group>
						</Form.Item>
					))}
				</Form>
			</Modal>
		</div>
	);
};
export default goodsSkuList;
